import datetime
import hashlib
import traceback

from common.response import Response
from db.aiomysql_connector import AioMysqlClient
from logger_config import logger
from services.cache_service import CacheUtils


class UserService(object):
    table = 'User'
    sql_error = '数据库查询错误,请检查字段'

    def __init__(self):
        self.sql_client: AioMysqlClient = CacheUtils.get('aiomysql_pool')

    async def get_all_user(self):
        try:
            sql = f'SELECT * FROM {self.table};'
            data = await self.sql_client.fetch_all(sql)
            return Response.success(data)
        except:
            logger.error(traceback.format_exc())
            return Response.fail(self.sql_error)

    async def find_user_by_id(self, user_id):
        try:
            sql = f'SELECT * FROM {self.table} WHERE id = {user_id}'
            user = await self.sql_client.fetch_one(sql)
            return user
        except:
            logger.error(traceback.format_exc())

    async def login_check(self, param: dict):
        try:
            username, password = param['username'], param['password']
            level = param['level']
            sql = f'SELECT * FROM {self.table} WHERE username=%s'
            user = await self.sql_client.fetch_one(sql, args=(username,))
            if not user:
                return Response.fail('该用户不存在')
            encrypt_password = self.encrypt_password(password)
            if encrypt_password != user['password']:
                return Response.fail('用户密码输入错误')
            if level != user['level']:
                return Response.fail('该等级下无该用户,请检查等级')
            data = {
                'id': user['id'],
                'username': user['username'],
                'level': user['level']
            }

            return Response.success(data)
        except:
            logger.error(traceback.format_exc())
            return Response.fail(self.sql_error)

    async def change_pwd(self, param):
        try:
            username = param.get('username')
            old_pwd = param.get('old_pwd')
            old_pwd = self.encrypt_password(old_pwd)
            new_pwd = param.get('new_pwd')
            new_pwd = self.encrypt_password(new_pwd)
            sql = f'select * FROM {self.table} WHERE username=%s'
            user = await self.sql_client.fetch_one(sql, username)
            if not user:
                return Response.fail('该用户不存在')

            if old_pwd != user['password']:
                return Response.fail('用户原密码错误')
            cur_time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            update_sql = f'UPDATE {self.table} SET password=%s,update_time=%s where username=%s'
            await self.sql_client.insert(update_sql, args=(new_pwd, cur_time_str, username))
            return Response.success(msg='密码已经修改,请重新登录')
        except:
            logger.error(traceback.format_exc())
            return Response.fail(self.sql_error)

    async def create_user(self, param: dict):
        try:
            encrypt_password = self.encrypt_password(param['pwd'])
            cur_time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            sql = f'INSERT INTO {self.table}(username,password,level,create_time) VALUES (%s,%s,%s,%s)'
            await self.sql_client.insert(sql, args=(param['username'], encrypt_password, param['level'], cur_time_str))
            return Response.success()
        except:
            logger.error(traceback.format_exc())
            return Response.fail(self.sql_error)

    @classmethod
    def encrypt_password(cls, password):
        # 创建 SHA-256 哈希对象
        hasher = hashlib.sha256()
        # 将密码作为字节串传递给哈希对象
        hasher.update(password.encode('utf-8'))
        # 获取哈希值的十六进制表示
        encrypted_password = hasher.hexdigest()
        return encrypted_password[:30]
